﻿using C1.WPF;
using C1.WPF.FlexGrid;
using Model;
using Model.Modules;
using SteelDetection.UIControl;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using Utility;
using ViewModel;
using Binding = System.Windows.Data.Binding;
using Proxy;

namespace SteelDetection
{
    /// <summary>
    /// PageHistory.xaml 的交互逻辑
    /// </summary>
    public partial class PageAnalysis : Page
    {
        List<UCRulerchart> charts;
        public PageAnalysis()
        {
            InitializeComponent();
            batchgrid.ColumnHeaders.Rows[0].Height = 40;
            var gr = new C1.WPF.FlexGrid.Row();

            gr.FontWeight = FontWeights.Bold;
            gr.Background = new SolidColorBrush((Color)System.Windows.Media.ColorConverter.ConvertFromString("#78a3a9"));
            gr.Foreground = new SolidColorBrush(Colors.White);
            batchgrid.ColumnFooters.Rows.Add(gr);
            batchgrid.CellFactory = new GradeCellFactory();
            batchgrid.ColumnHeaders.Rows.Add(new C1.WPF.FlexGrid.Row());
            
            Loaded += (s,e)=> {
                
            };


            batchgrid.Loaded += (s, e) =>
            {
                //batchgrid.ColumnFooters.Columns.Add(new Column());

                // add the row to the ColumnFooters GridPanel

                
            };

        }

        private void batchgrid_ItemsSourceChanged(object sender, EventArgs e)
        {
            grouptoggle.IsChecked = false;
            ResourceDictionary resourceDictionary = new ResourceDictionary();
            resourceDictionary.Source = new Uri("/SteelDetection;component/Dic/BaseDictionary.xaml", UriKind.Relative); // 替换 YourAssemblyName 为你的程序集名称
            batchgrid.AllowMerging = AllowMerging.AllHeaders;
            batchgrid.ColumnHeaders.Rows[0].AllowMerging = true;
            var dv = (batchgrid.ItemsSource as ICollectionView).SourceCollection as DataView;
            for (int i=0;i<dv.Table.Columns.Count;i++)
            {
                var col = dv.Table.Columns[i];
                //Diff 兴橙，南南铝用main_id，永钢用user_custom_id
                if (col.ColumnName == "main_id") {
                    batchgrid.Columns[i].Visible = false;
                }
                else if (col.ColumnName == "user_custom_rolled_id")
                {
                    batchgrid.Columns[i].Header = "轧批计划号";
                    batchgrid.Columns[i].Width = new GridLength(180);
                }
                else if (col.ColumnName == "user_custom_id")
                {
                    batchgrid.Columns[i].Header = "批次号";
                    batchgrid.Columns[i].Width = new GridLength(180);
                }
                else if (col.ColumnName == "insert_time")
                {
                    batchgrid.Columns[i].Header = "插入时间";
                    batchgrid.Columns[i].Width = new GridLength(160);
                    batchgrid.Columns[i].Format= "yyyy-MM-dd HH:mm:ss";
                }
                else if (col.ColumnName == "cz")
                {
                    batchgrid.Columns[i].Header = "材质";
                    batchgrid.Columns[i].Width = new GridLength(80);
                    //Diff 马钢不展示材质
                    batchgrid.Columns[i].Visible = false;
                }
                else if (col.ColumnName == "gg")
                {
                    batchgrid.Columns[i].Header = "规格";
                    batchgrid.Columns[i].Width = new GridLength(80);
                    //Diff 马钢不展示规格
                    batchgrid.Columns[i].Visible = false;
                }
                else if (col.ColumnName == "grade") 
                {
                    batchgrid.Columns[i].Header = "分级";
                    batchgrid.Columns[i].Width = new GridLength(80);
                }
                else if (col.ColumnName == "score")
                {
                    batchgrid.Columns[i].HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    batchgrid.Columns[i].GroupAggregate = Aggregate.Average;
                    batchgrid.Columns[i].Format = "#####.##";
                    batchgrid.Columns[i].Header = "分数";
                    batchgrid.Columns[i].Width = new GridLength(80);
                }
                else if (col.ColumnName == "defect_img_ratio")
                {
                    batchgrid.Columns[i].Header = "缺陷图片\r\n占比(%)";
                    batchgrid.Columns[i].HeaderTextWrapping = true;
                    batchgrid.Columns[i].HeaderHorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                    batchgrid.Columns[i].Width = new GridLength(80);
                }
                else
                {
                    batchgrid.Columns[i].HorizontalAlignment =  System.Windows.HorizontalAlignment.Right;
                    batchgrid.Columns[i].GroupAggregate = Aggregate.Sum;
                    batchgrid.Columns[i].Format = "#####.##;;''";

                    batchgrid.Columns[i].Width= new GridLength(45);
                    batchgrid.Columns[i].AllowMerging = true;
                    switch (col.ColumnName.Split('_')[1])
                    {
                        case "alert":
                            batchgrid.Columns[i].Foreground = resourceDictionary["Alarm_Brush"] as Brush;
                            batchgrid.ColumnHeaders[1, i] = "报警";
                            break;
                        case "warning":
                            batchgrid.Columns[i].Foreground = resourceDictionary["Warning_Brush"] as Brush;
                            batchgrid.ColumnHeaders[1, i] = "警告";
                            break;
                        case "suspected":
                            batchgrid.Columns[i].Foreground = resourceDictionary["Suspected_Brush"] as Brush;
                            batchgrid.ColumnHeaders[1, i] = "疑似";
                            break;
                    }
                    //batchgrid.Columns[i].Header = StaticData.DefectTypes.Where(t => t.id.ToString() == col.ColumnName.Split('_')[0]).First().name;
                    batchgrid.ColumnHeaders[0,i]= StaticData.DefectTypes.Where(t => t.id.ToString() == col.ColumnName.Split('_')[0]).First().name;
                    //var colinfo = StaticData.DefectTypes.Where(t => t.id.ToString() == (col as DataColumn).ColumnName);
                    //if (colinfo.Any())
                    //{

                    //}

                    //batchgrid.Columns[i].Header = colinfo.First().name;
                    //batchgrid.Columns[i].Width = new GridLength(60);
                    //batchgrid.Columns[i].HeaderTextWrapping = true;
                }

            }
            

            float goodcount=dv.Table.AsEnumerable().Where(t => t["grade"].ToString()=="优秀"|| t["grade"].ToString() == "良好").Count();
            var goodrate = goodcount / dv.Table.Rows.Count;
            var row = batchgrid.ColumnFooters.Rows[0];
            row[1] = "合格率:";
            row[2] = goodrate.ToString("P2");


        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV文件 (*.csv)|*.csv";
            saveFileDialog.FileName = $"{((DateTime)startpicker.DateTime).ToString("yyyy-MM-dd")}~{((DateTime)endpicker.DateTime).ToString("yyyy-MM-dd")}缺陷分类统计结果";
            if (saveFileDialog.ShowDialog()== DialogResult.OK)
            {
                batchgrid.Save(saveFileDialog.FileName, FileFormat.Csv);
                System.Diagnostics.Process.Start(saveFileDialog.FileName);
            }

        }

        public class GradeCellFactory : CellFactory
        {
            public override void CreateCellContent(C1FlexGrid grid, Border bdr, CellRange rng)
            {
                var rowdata = grid.Rows[rng.Row].DataItem;
                if (grid.Columns[rng.Column].ColumnName == "grade" )
                {
                    var tb = new TextBlock();
                    tb.SetBinding(TextBlock.TextProperty, new Binding("grade"));
                    Binding binding = new Binding("grade");
                    binding.Converter = new BatchGradeColorConverter();
                    tb.SetBinding(TextBlock.ForegroundProperty, binding);
                    bdr.Child = tb;
                }
                else
                {
                    base.CreateCellContent(grid, bdr, rng);
                }
            }
        }


        private async void batchgrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var hitinfo = batchgrid.HitTest(e);
            if (batchgrid.Columns[hitinfo.Column].ColumnName == "user_custom_id")
            {
                var ty = hitinfo.Panel.CellType;
                try
                {
                    var batchid = batchgrid.Cells[hitinfo.Row, "main_id"].ToString();
                    VM_WindowMain.GetInstance().GotoHistoryDefect(batchid, "");
                }
                catch (Exception ex)
                {
                }


            }
            
        }

        private void ToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            var view = (batchgrid.ItemsSource as ICollectionView);
            var gd=view.GroupDescriptions;
            gd.Add(new PropertyGroupDescription("user_custom_rolled_id"));  // grand total group
            gd[0].GroupNameFromItem ("AAAAA", 0, CultureInfo.CurrentCulture);
            batchgrid.AreRowGroupHeadersFrozen = false;
            batchgrid.GroupHeaderConverter = new BathGroupHeaderConverter();
            batchgrid.CollapseGroupsToLevel(0);
            batchgrid.Columns["user_custom_rolled_id"].Foreground = Brushes.Transparent;

        }

        private void ToggleButton_Unchecked(object sender, RoutedEventArgs e)
        {
            (batchgrid.ItemsSource as ICollectionView).GroupDescriptions.Clear();
            batchgrid.Columns["user_custom_rolled_id"].Foreground = Brushes.White;
        }
    }

    public class BathGroupHeaderConverter : IValueConverter
    {
        public string NullEmptyString { get; private set; }

        public new object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            NullEmptyString= "未知";
            if (parameter is GroupRow groupRow && targetType == typeof(string))
            {
                CollectionViewGroup group = groupRow.Group;
                if (group != null)
                {
                    ICollectionView collectionView = groupRow.Grid.CollectionView;
                    object name = group.Name;
                    int itemCount = group.ItemCount;
                    string text = "项";
                    string text2 = ((name != null) ? name.ToString() : string.Empty);
                    if (text2 == "{DependencyProperty.UnsetValue}")
                    {
                        text2 = string.Empty;
                    }

                    PropertyGroupDescription propertyGroupDescription = ((collectionView != null && groupRow.Level < collectionView.GroupDescriptions.Count) ? (collectionView.GroupDescriptions[groupRow.Level] as PropertyGroupDescription) : null);
                    if (name is IFormattable formattable && propertyGroupDescription != null && groupRow.Grid.Columns.Contains(propertyGroupDescription.PropertyName))
                    {
                        Column column = groupRow.Grid.Columns[propertyGroupDescription.PropertyName];
                        if (column != null && !string.IsNullOrEmpty(column.Format) && formattable != null)
                        {
                            try
                            {
                                text2 = formattable.ToString(column.Format, culture);
                            }
                            catch
                            {
                            }
                        }
                    }

                    if (propertyGroupDescription == null)
                    {
                        return $"{name } ({itemCount:n0} {text})";
                    }
                    return $"{(string.IsNullOrEmpty(text2) ? NullEmptyString : text2)}   (共 {itemCount:n0} {text})";
                    //return $"{(propertyGroupDescription.PropertyName== "user_custom_rolled_id"? "轧批计划号" : propertyGroupDescription.PropertyName)}: {(string.IsNullOrEmpty(text2) ? NullEmptyString : text2)}   (共 {itemCount:n0} {text})";
                }
            }

            return value;

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
   
    }
